#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "ts.h"
#include "hires.h"
#include "sockets.h"
#include "netopt.h"

char http[4096];

int main(int ac,char** av){
	struct netopt* op = netopt(ac,av);
	int sock, result, len, answer_len;
	double start,end;
	char* answer_ptr;
	char headers[4096];
	if(op == 0){
		return 1;
	}
	if(0 == *op->host){
		printf("need host\n");
		return 1;
	}
	if(0 == *op->addr){
		printf("need addr\n");
		return 1;
	}
	if(0 == op->port){
		printf("need port\n");
		return 1;
	}
	if(0 == *op->url){
		printf("need url\n");
		return 1;
	}
	if(op->count == 0){
		op->count = 1;
	}
	if(op->last == -1){
		*headers = 0;
	}else{
		int hl = 0;
		for(int i = op->last; i < ac;i++){
			sprintf(headers+hl,"%s\n",av[i]);
			hl = strlen(headers);
		}
	}

	sprintf(http,"GET %s HTTP/1.0\n%sHost: %s\nConnection: close\n\n",op->url,headers,op->host);
	len = strlen(http);
	if(op->timing){
		start = hires();
	}
	
	for(int i = 0; i < op->count; i++){
		if(op->verbose){
			printf("Try: \n%s\n",http);
		}
		sock = make_connect(op->addr, op->port, op->laddr, op->lport);
		if(!sock){
			return 1;
		}
		result = send_message(sock,http,len);
		if(!result){
			return 1;
		}
		result = recv_message(sock,&answer_ptr,&answer_len,&read_all);
		if(!result){
			free(answer_ptr);
			return 1;
		}
		answer_ptr[answer_len] = 0;
		if(op->verbose){
			printf(answer_ptr);
		}
		close_connect(sock);
	}
	if(op->timing){
		end = hires();
		printf("Res: count=%d time=%f speed=%f\n",op->count,end-start,op->count/(end-start));
	}
	return 0;
}
